﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OptimumInfra.ViewData;

namespace OptimumInfra.Models
{
    public class EmailRepository
    {
        private OptimumDataContext op = new OptimumDataContext();

        public IEnumerable<Newsletter> GetAllEmail()
        {
            return (from r in op.Newsletters
                         select r).ToList();
        }
        public string GetAllReceivers()
        {
            var result = from r in op.Newsletters
                    select r;
            string ret = "";
            foreach (var r in result)
            {
                ret += r.Email + ",";
            }
            String delim = ",";

            return ret.TrimEnd(delim.ToCharArray());
        }

        public void CreateNewEmail(Newsletter email)
        {
            if(!IsEmailExisted(email.Email)) {
                op.Newsletters.InsertOnSubmit(email);
                op.SubmitChanges();
            }
        }

        public bool IsEmailExisted(string email)
        {
            return this.op.Newsletters.Any(n => n.Email == email);
        }

        public void DeleteEmail(int emailId)
        {
            Newsletter n = GetEmailById(emailId);
            op.Newsletters.DeleteOnSubmit(n);
            op.SubmitChanges();
        }
      

        public void UpdateEmail(Newsletter e)
        {
            var email = op.Newsletters.Single(a => a.Id == e.Id);
            email.Email = e.Email;
            op.SubmitChanges();
        }

        public Newsletter GetEmailById(int id)
        {
            var result = op.Newsletters.SingleOrDefault(a => a.Id == id);
            return result;

        }
    }
}